package easy;

public class Solution_1592 {

    public String reorderSpaces(String text) {
        text += " ";
        int[] begin = new int[101];
        int[] end = new int[101];
        char[] chars = text.toCharArray();
        int count_1 = 0, count_2 = 0;
        for (int i = 0, count = 0; i < chars.length; i++) {
            char c = chars[i];
            if (c == ' ') {
                count_1++;
                if (count > 0) {
                    begin[count_2] = i - count;
                    end[count_2] = count;
                    count_2++;
                    count = 0;
                }
            } else {
                count++;
            }
        }
        count_1--;
        int count = 0;
        int mod = count_1;
        if (count_2 > 1) {
            count = count_1 / (count_2 - 1);
            mod = count_1 % (count_2 - 1);
        }
        StringBuffer buffer = new StringBuffer();
        for (int i = 0; i < count_2; i++) {
            if (i > 0) {
                for (int j = 0; j < count; j++) {
                    buffer.append(" ");
                }
            }
            buffer.append(chars, begin[i], end[i]);
        }
        for (int i = 0; i < mod; i++) {
            buffer.append(" ");
        }
        return buffer.toString();
    }

    public static void main(String[] args) {
        Solution_1592 model = new Solution_1592();
        System.out.println(model.reorderSpaces("  this   is  a sentence "));
        System.out.println(model.reorderSpaces(" practice   makes   perfect"));
        System.out.println(model.reorderSpaces("hello   world"));
        System.out.println(model.reorderSpaces("  walks  udp package   into  bar a"));
        System.out.println(model.reorderSpaces("a"));
    }
}
